<template>
  <FIForm
    v-show="searchStatus"
    class="search-form"
    :class="{ 'search-form-bg': showBgColor }"
    ref="formRef"
    label-position="right"
    :inline="true"
    :model="formValue"
    :rule="rules"
    v-bind="$attrs"
    v-on="$attrs"
  >
    <el-row :gutter="10" class="search-form__row" :class="isCollapse ? 'search-form__close' : 'search-form__open'">
      <slot></slot>
      <slot name="dynamicForm">
        <template v-if="isBindTable && showDynamic">
          <template v-for="item in columnSearchList" :key="item.prop">
            <el-col
              v-if="item.showHighSearch"
              :span="item.filterMode != 'number-range' ? wrapperSpan : 8"
              class="flex-center"
            >
              <FIFormItem :name="item.prop" :label="item.label" deletable @delete-item="deleteFilterItem">
                <filterCell :column-item="item" :modelValue="item.modelValue" :teleported="true"></filterCell>
              </FIFormItem>
            </el-col>
          </template>
        </template>
        <el-col :span="wrapperSpan" v-for="n in emptySearchItem" :key="n"></el-col>
      </slot>
      <el-col
        v-if="showFotter"
        :span="wrapperSpan"
        class="search-form__btn flex-center"
        :class="{ 'search-form__btn-close': isCollapse, 'search-form__btn-bg': showBgColor && isCollapse }"
      >
        <el-form-item label="">
          <slot name="collapseBtn">
            <el-badge v-if="isCollapse && showCollapse" :value="totalSearchNum" type="primary">
              <FIButton @click="closeForm" style="width: 32px" iconBtnName="icon-gaojishaixuanzhankaisvg"></FIButton>
            </el-badge>
            <FIButton
              v-if="!isCollapse && showCollapse"
              @click="closeForm"
              style="width: 32px"
              iconBtnName="icon-gaojishaixuan"
            ></FIButton>
          </slot>
          <slot name="resetBtn">
            <FIResetBtn
              :class="isCollapse ? 'search-form__btn-collapse' : ''"
              v-model:modelValue="copyFormValue"
              :resetExcludeValues="excludeValues"
              :text="resetBthText"
              :restBinds="restBtnBinds"
              @handleReset="handleReset"
            ></FIResetBtn>
          </slot>
          <slot name="queryBtn">
            <FIButton
              v-if="queryAuth"
              :id="queryId"
              customType
              type="primary"
              prefixIcon="icon-chaxun"
              @click="handleFinish"
              >查询</FIButton
            >
            <FIButton v-else type="primary" prefixIcon="icon-chaxun" @click="handleFinish">查询</FIButton>
          </slot>
          <slot name="others"> </slot>
        </el-form-item>
      </el-col>
    </el-row>
  </FIForm>
</template>
<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import FIButton from '@/components/FIButton.vue'
import filterCell from '@/components/FITable/filterCell.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIForm from '@/components/FIForm.vue'
import FIResetBtn from '@/components/FIResetBtn.vue'

import LocalCache from '@/utils/cache'
import { getHasSearchValues, getDynamicQueryParams } from '@/utils/common'
import { useTableStore, removePrefixesFn } from '@/stores/table'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
const route = useRoute()
const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  formValue: {
    type: Object,
  },
  rules: {
    type: Object,
  },
  collapse: {
    type: Boolean,
    default: true,
  },
  // 常规默认搜索项个数
  defaultFormNum: {
    type: Number,
    default: 0,
  },
  // 搜索条件有值个数
  searchNum: {
    type: Number,
    default: 0,
  },
  showFotter: {
    type: Boolean,
    default: true,
  },
  wrapperSpan: {
    type: [String, Number],
    default: 8,
  },
  // // 重置排除字段
  // resetExcludeValues: {
  //   type: Array,
  //   default: () => [],
  // },
  // 计算有值个数，重置排除字段（非表单中搜索条件字段）
  excludeValues: {
    type: Array,
    default: () => [],
  },
  dynamicSearchForm: {
    type: Array,
    default: () => [],
  },
  // 对应table 列对象
  tableColumn: {
    type: Array,
    default: () => {
      return []
    },
  },
  // 是否展示可折叠按钮
  showCollapse: {
    type: Boolean,
    default: true,
  },
  // 是否显示高级查询配置
  showDynamic: {
    type: Boolean,
    default: true,
  },
  // 是否显示背景色
  showBgColor: {
    type: Boolean,
    default: true,
  },
  // 重置按钮文案
  resetBthText: {
    type: String,
    default: '',
  },
  // 重置按钮自定义属性集合
  restBtnBinds: {
    type: Object,
    default: () => {
      return {
        style: { width: '32px' },
      }
    },
  },
  // 查询按钮id
  queryId: {
    type: String,
    default: 'query',
  },
  // 查询按钮是否需要权限
  queryAuth: {
    type: Boolean,
    default: true,
  },
})

const emit = defineEmits(['reset', 'submit', 'update:formValue', 'update:columns', 'deleteFilterItem'])
const isCollapse = ref(props.collapse)
const formRef = ref(null)
const tableStore = useTableStore()
const { tableCaches } = storeToRefs(tableStore)

// 验证完成并提交
const handleFinish = () => {
  // const dynamicQueryArr = getDynamicQueryParams(columnSearchList.value)
  // emit('submit', isBindTable.value ? dynamicQueryArr : null)
  emit('submit', 'query', columnSearchList.value)
}
const closeForm = () => {
  isCollapse.value = !isCollapse.value
}
const initColumnSearch = (arr: []) => {
  let tempArr = []
  Array.isArray(arr) &&
    arr.length &&
    arr.forEach((item: any) => {
      if (item?.filterable) {
        item.showHighSearch = false
        tempArr.push(item)
      }
    })
  return tempArr
}
// 缓存的列筛选数据同步到列筛选上
const initColumnSearchToColumnData = (arr) => {
  Array.isArray(arr) &&
    arr.length &&
    arr.forEach((item: any) => {
      Array.isArray(props.tableColumn) &&
        props.tableColumn.forEach((cloumnItem: any) => {
          if (cloumnItem.prop === item.prop) {
            cloumnItem.modelValue = item.modelValue
            cloumnItem.showHighSearch = item.showHighSearch
          }
        })
    })
}
// 获取搜索表单显示隐藏状态
let tempId = removePrefixesFn(`${props.id}_search_show`)
const searchStatus = ref(true)

watch(
  () => tableCaches.value,
  (newValue) => {
    searchStatus.value = newValue[tempId] == undefined ? true : newValue[tempId]
  },
  { immediate: true, deep: true }
)
// 列筛选数组
// const columnSearchList = ref(initColumnSearch(props.tableColumn))
const columnSearchList = computed(() => {
  return props.tableColumn
})
// watch(
//   () => props.tableColumn,
//   (newValue, oldValue) => {
//     console.log('columnSearchList 已触发', newValue, oldValue)
//   },
//   { immediate: true, deep: true }
// )
watch(
  () => columnSearchList.value,
  (newValue, oldValue) => {},
  { immediate: true, deep: true }
)
const userData = LocalCache.getCache('user')
const userId = userData.userId
if (LocalCache.getCache(`${userId}-${route.path}-${removePrefixesFn(props.id)}-columns`)) {
  const data = LocalCache.getCache(`${userId}-${route.path}-${removePrefixesFn(props.id)}-columns`)
  initColumnSearchToColumnData(data)
}
const copyFormValue = computed({
  get() {
    return props.formValue
  },
  set(newValue) {
    // copyFormValue.value = newValue
    emit('update:formValue', newValue)
  },
})
watch(
  () => props.formValue,
  (newValue, oldValue) => {
    // 实时缓存搜索数据---------
    if (oldValue) {
      const userData = LocalCache.getCache('user')
      const userId = userData.userId
      LocalCache.setCache(`${userId}-${route.path}-${removePrefixesFn(props.id)}`, newValue)
    }
  },
  { immediate: true, deep: true }
)
watch(
  () => copyFormValue.value,
  (newValue, oldValue) => {
    // emit('update:formValue', newValue)
  },
  { immediate: true, deep: true }
)
watch(
  () => columnSearchList.value,
  (newValue, oldValue) => {
    if (oldValue) {
      const userData = LocalCache.getCache('user')
      const userId = userData.userId
      LocalCache.setCache(`${userId}-${route.path}-${removePrefixesFn(props.id)}-columns`, newValue)
    }
    emit('update:columns', newValue)
  },
  { deep: true }
)

// 重置高级选项
const handleReset = () => {
  Array.isArray(columnSearchList.value) &&
    columnSearchList.value.forEach((item) => {
      if (item.showHighSearch) {
        item.modelValue = []
      }
    })
  emit('reset')
}
// 删除筛选项
const deleteFilterItem = (e) => {
  const columnIndex = columnSearchList.value.findIndex((column) => column?.prop === e)
  if (columnIndex !== -1) {
    let currentValue = columnSearchList.value[columnIndex].modelValue
    switch (typeof currentValue) {
      case 'object':
        if (currentValue !== null && !Array.isArray(currentValue)) {
          // 对象的情况，清空对象的所有属性值
          for (const key in currentValue) {
            if (currentValue.hasOwnProperty(key)) {
              // currentValue[key] = false; // 假设属性都是布尔类型，如果不是，根据实际情况调整
              if (typeof currentValue[key] === 'boolean') {
                currentValue[key] = false // 如果属性是布尔类型，设为false
              } else {
                // 如果是基本类型、null、Date或数组，设为空值
                currentValue[key] = ''
              }
            }
          }
        } else if (Array.isArray(currentValue)) {
          // 数组的情况
          currentValue.length = 0 // 清空数组
        }
        break
      case 'boolean':
        currentValue = false
        break
      default:
        currentValue = ''
        break
    }
    columnSearchList.value[columnIndex].modelValue = currentValue
    columnSearchList.value[columnIndex].showHighSearch = false
  }
  handleFinish()
  // emit('deleteFilterItem', e)
}
const emptySearchItem = computed(() => {
  let count = columnSearchList.value.filter((item: any) => item.showHighSearch === true).length
  // 下面是常规搜索框的个数
  let totalSearchCount = 0
  if (props.defaultFormNum) {
    // 如果父组件传递了常规搜索框的个数，则使用父组件传递的个数
    totalSearchCount = isBindTable.value ? props.defaultFormNum + count : props.defaultFormNum
  } else {
    const excludedProperties = ['dynamicParams', 'orderbyParams', 'current', 'size', ...props.excludeValues]
    const defaultNum = countExcludedProperties(props.formValue, excludedProperties)
    totalSearchCount = isBindTable.value ? defaultNum + count : props.defaultFormNum
  }
  return 2 - (totalSearchCount % 3)
})
const totalSearchNum = computed(() => {
  // table动态条件有值个数
  let columnSearchCount = columnSearchList.value.filter((item: any) => {
    const modelValue = item?.modelValue
    if (item?.showHighSearch === true) {
      if (typeof modelValue === 'object' && modelValue !== null) {
        return Object.keys(modelValue).some((key: string) => {
          const value = modelValue[key]
          if (Array.isArray(value)) {
            return value.length > 0
          } else {
            return !!value // 如果不是数组，检查其值是否为真
          }
        })
      } else if (typeof modelValue === 'string' || typeof modelValue === 'number') {
        return !!modelValue // 如果 modelValue 是基本类型，检查其值是否为真
      }
    }
    return false
  }).length
  let tempNum = getHasSearchValues(props.formValue, 24 / props.wrapperSpan, props.excludeValues)
  if (props.searchNum) {
    tempNum = props.searchNum
  }
  return isBindTable.value ? tempNum + columnSearchCount : tempNum
  // return isBindTable.value ? props.searchNum + columnSearchCount : props.searchNum
})
// 计算需要搜索的列数
const countExcludedProperties = (query, excludedProperties) => {
  const keys = Object.keys(query)
  let count = 0
  for (let key of keys) {
    if (!excludedProperties.includes(key)) {
      count++
    }
  }
  return count
}
// 是否有绑定table
const isBindTable = computed(() => !!props.id)
</script>
<style lang="less" scoped>
.search-form {
  padding: 24px 30px 10px;
  border-radius: 2px;
  //   background: #fff;
  //   width: 932px;#fbeaec
  // height: 136px;

  border-radius: 6px;
  &:hover {
    box-shadow: 1px 4px 12px 0px rgba(0, 0, 0, 0.16);
    opacity: 0.8;
  }
  ::v-deep(.el-form-item) {
    margin-bottom: 18px !important;
    .el-form-item__label {
      width: 100px;
    }
    .el-form-item__content {
      width: 220px;
    }
  }
  ::v-deep(.el-input .el-input__wrapper) {
    width: 220px;
  }
  ::v-deep(.el-range-editor) {
    width: 220px;
  }
}
.search-form-bg {
  background: linear-gradient(182deg, #ffeeee 0%, #ffffff 100%);
  background: linear-gradient(182deg, var(--el-color-primary-light-9) 0%, #ffffff 100%);
}
.search-form__row {
  width: 100%;
}
.search-form__close {
  height: 40px;
  max-height: 40px;
  overflow: hidden;
}
.search-form__btn {
  // text-align: right;
  padding-left: 116px !important;
  display: grid !important;
  color: var(--el-color-primary);

  ::v-deep(.el-form-item) {
    margin-bottom: 18px !important;
    .el-form-item__content {
      width: 210px;
      .el-badge .el-badge__content {
        top: 10px !important;
      }
    }
  }
}
.search-form__btn-close {
  background: #fff;
  position: absolute;
  top: 0;
  right: 10px;
  width: 100%;
  height: 50px;
}
.search-form__btn-bg {
  background: linear-gradient(182deg, #ffeeee 0%, #ffffff 100%);
  background: linear-gradient(182deg, var(--el-color-primary-light-9) 0%, #ffffff 100%);
}
.search-form__btn-collapse {
  margin-left: 16px !important;
}
.search-form__btn-collapse {
  margin-left: 10px;
  padding: 0 10px;
  cursor: pointer;
  &:hover {
    background: var(--el-color-primary-light-8);
    border-radius: 4px;
  }
}
.search-form__num {
  margin-left: 8px;
  font-size: 14px;
}
</style>
